﻿/**
 * particles
 *
 * @author		Duarte Peixinho
 * @version		1.0
 */

package com.duartepeixinho.particles 
{
	import flash.display.Bitmap;
	import flash.display.DisplayObject;
	import flash.events.Event;
	import com.duartepeixinho.particles.core.CreateParticlesFromImage;
	
	public class AnimationParticles extends CreateParticlesFromImage
	{
		
		private var _xv:Number=0;
		private var _yv:Number=0;
		private var _floor:Number;
		private var _bitmapPixels:Array = new Array();
		private var _animation:Boolean = false;
		private var checkAnimation:uint;
		private var _animationStart:Boolean = false;
		private const GRAVITY:Number = 0.98;
		private const xForce:Number = 10;
		private const yForce:Number = -20;
		private var _end:Boolean = false;
		
		/**
		 * 
		 * @param	floor		Number			y position where the particles hit the floor
		 * @param	object		DisplayObject	Object that is going to be pixelate and animate
		 * @param	xPixel		Number			particle width
		 * @param	yPixel		Number			particle height
		 */
		
		public function AnimationParticles(floor:Number, object:DisplayObject, xPixel:uint, yPixel:uint) 
		{
			//creates pixels
			super(object, xPixel, yPixel);
			
			_floor = floor;
			
		}
		
		/**
		 * startAnimation
		 */
		public function startAnimation():void {
			
			//loop to animation
			addEventListener(Event.ENTER_FRAME, loop);
			
			for (var i:uint; i < _pixels.length; i++) {	
				_pixels[i].xv = Math.random() * xForce - xForce/2;
				_pixels[i].yv = Math.random() * yForce;
				
				if (!_animationStart) {
					var bitmap:Bitmap = _pixels[i].show();
				
					_bitmapPixels[i] = bitmap;				
					addChild(_bitmapPixels[i]);
				}
				
				_bitmapPixels[i].x = _pixels[i].x;
				_bitmapPixels[i].y = _pixels[i].y;
				
			}
			checkAnimation = _pixels.length;
			if (!_animationStart) _animationStart = true;
			_animation = true;			
		} 
		
		/**
		 * Loop
		 */ 
		private function loop(e:Event):void {
			if (_animation) {
				var validateAnimation:uint = 0;
				for (var i:uint; i < _pixels.length; i++) {	
					if (_bitmapPixels[i].y < _floor) {
						_bitmapPixels[i].x += _pixels[i].xv;
						_bitmapPixels[i].y += _pixels[i].yv;
						_pixels[i].yv += GRAVITY;
					}
					else validateAnimation++;
				}				
				if (validateAnimation == checkAnimation) {
					_animation = false;
					_end = true;
					removeEventListener(Event.ENTER_FRAME,loop);
				}
			}
		}
		/**
		 * 
		 * @return				Boolean		Status of the end of the animation
		 */
		public function getAnimationStatus():Boolean {
			return _end;
		}
	}
}